package com.shop.ken.common.cors;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 项目名称：shop-server
 * 文件名称：CORSFilter
 * 日期：2017/9/8
 * Copyright ©2017, 广州职赢未来信息科技有限公司 All Rights Reserved.\
 * <p>
 * <p>
 * 功能描述：跨域过滤器
 * 创建人: 霍梓潮
 * 创建时间：2017/9/8
 **/
@WebFilter(filterName = "CORSFilter" , urlPatterns = "/*")
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type,token");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        if (!"OPTIONS".equals(req.getMethod().toUpperCase())) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
